const Stomp = require('./stomp.min.js').Stomp;

let socketOpen = false
let socketMsgQueue = []
function getSocketWS(url) {

  function numberString(e) {
    var t = ("" + (e - 1)).length;
    return (new Array(t + 1).join("0") + number(e)).slice(-t)
  }


  function string(e) {
    var s = 'abcdefghijklmnopqrstuvwxyz012345'
    for (var t = s.length, n = randomBytes(e), r = [], o = 0; o < e; o++) r.push(s.substr(n[o] % t, 1));
    return r.join("")
  }

  function randomBytes(e) {
    for (var t = new Array(e), n = 0; n < e; n++) t[n] = Math.floor(256 * Math.random());
    return t
  }

  function number(e) {
    return Math.floor(Math.random() * e)
  }
  //http转化成ws
  let num = numberString(1e3)
  let socketUrl = /http/.test(url) ? url.replace('http', 'ws') : ''
  //拼接后缀
  // socketUrl = `${socketUrl}/${num}/${string(8)}/websocket`
  socketUrl = `${socketUrl}/websocket`
  return socketUrl
}
export default {
  client: null,
  init(url, header ,connectWS) {
    if (this.client) {
      return Promise.resolve(this.client)
    }

    return new Promise((resolve, reject) => {
      const ws = {
        send: this.sendMessage,
        onopen: null,
        onmessage: this.getMessage,
      }
      let socketUrl=getSocketWS(url)
      wx.connectSocket({ url:socketUrl, header })
      wx.onSocketOpen(function (res) {
        console.log('WebSocket连接已打开！', res)
        socketOpen = true
        for (let i = 0; i < socketMsgQueue.length; i++) {
          ws.send(socketMsgQueue[i])
        }
        socketMsgQueue = []
        ws.onopen && ws.onopen()
      })

      wx.onSocketMessage(function (res) {
          // ios 缺少 0x00 导致解析失败
        if (res && res.data) {
          let value = res.data;
          let code = value.charCodeAt(value.length - 1);
          if (code !== 0x00) {
            value += String.fromCharCode(0x00);
            res.data = value;
          }
        }
        ws.onmessage && ws.onmessage(res)
      })

      wx.onSocketError(function (res) {
        console.log('WebSocket 错误！', res)
      })

      wx.onSocketClose((res) => {
        this.client = null
        socketOpen = false
        console.log('WebSocket 已关闭！', res)
        if(res.code !== 1000){
          setTimeout(()=>{
            connectWS&&connectWS()
          },3000)
        }
      })
      Stomp.setInterval = function (interval, f) {
        return setInterval(f, interval)
      }
      Stomp.clearInterval = function (id) {
        return clearInterval(id)
      }
      const client = (this.client = Stomp.over(ws))
      console.log(client)
      // 关闭连接
      client.close = () =>{
        wx.closeSocket()
      }
      console.log(header)
      client.connect(header, function () {
        console.log('stomp connected')
        resolve(client)
      })
    })
  },
  sendMessage(message) {
    if (socketOpen) {
      wx.sendSocketMessage({
        data: message,
      })
    } else {
      socketMsgQueue.push(message)
    }
  },
  getMessage(message){
    console.log("从Rabbit获取到的消息", message)
  },
}